package thread.test2Lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * <p/>
 * ReadWriteLock 接口  （读锁和写锁分开）
 * 实现类 ReentrantReadWriteLock
 */
public class LockTest2 {


    public static void main(String[] args) {
        //默认非公平锁，可以传入参数true表示公平锁
        final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        //线程1
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //获取锁，会一直等待
                    lock.readLock().lock();
                    for (int i = 0; i < 100; i++) {
                        System.out.println("aaaa"+Thread.currentThread().getName());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.readLock().unlock();
                }
            }
        }).start();


        //线程2
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //  如果使用lock.writeLock().lock(); 就不会有并发发生了。
                    lock.readLock().lock();
                    for (int i = 0; i < 100; i++) {
                        System.out.println("bbbbb"+Thread.currentThread().getName());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.readLock().unlock();
                }
            }
        }).start();
    }
}
